/**
 * jQuery Social Modal Box
 *
 * Version: 1.0
 * (c) 2011 PixelsHub (pixelshub.com)
 * All rights reserved
 * License: http://codecanyon.net/wiki/support/legal-terms/licensing-terms/
 *
 * Needs jQuery Cookie plugin by Klaus Hartl (stilbuero.de)
 */
 
		
		
var modals = new Array();
var test = 0;
$.fn.socialmodal = function(params) {

	var defaults = {
		uniqueName:		'socialmodal',
        title:			'jQuery Social Modal Box',
		subtitle:		null,
		content:		null,
		count: 			0,
		warning:		'We need cookies to save your decision',
		facebook: 		null,
		plusone: 		null,
		twitter:		null,
		opacity: 		'0.4',
		manualClose:	false,
		onclick:		null,
		afterDocReady:	false,
		callback:		function() {},
	};
	
	// build main options
	var o = $.extend({}, defaults, params);
		
	// read cookies
	var cookie = ReadCookies();
	if(cookie==false && $('#'+o.uniqueName).length==0 && (o.facebook!=false || o.plusone!=false || o.twitter!=false)) {
		// create modal box
			$('body').prepend('<div class="blackout" id="'+o.uniqueName+'Blackout"></div><div id="'+o.uniqueName+'Outer" class="socialmodalOuter"><div id="'+o.uniqueName+'" class="socialmodal"></div></div>');	
			
			var main = '#'+o.uniqueName;
			var blackout = main+'Blackout';
			var outer = main+'Outer';
			var share = main+' .share';
			var close = main+'Close';
			var footer = main+' .footer';
			
			$(blackout)	.css({'height':$(document).height()});
			$(main)	.append('<div class="title">'+o.title+'</div>');
						
			// check if cookies are enabled
			$.cookie('cookietest', '1');
			var cookiesEnabled = $.cookie('cookietest');
			if(!cookiesEnabled) {
				$(main).append('<p class="warning">'+o.warning+'</p>');
			}
			$.cookie('cookietest', null);
				
			if (o.subtitle!=null) $(main).append('<div class="subtitle">'+o.subtitle+'</div>');
				
			if (o.content!=null) $(main).append('<div class="content">'+o.content+'</div>');
			
			// FIX: duplicating g:plusone in IE
			$(main).append('<div class="share"></div><div class="footer"></div>');
				
			// facebook like
			if (o.facebook!=false) { 
				$(share).append('<div class="button like"><fb:like id="fbLikeButton" href="'+o.facebook+'"send="false" layout="button_count" width="50" show_faces="false"></fb:like></div>'); 
				if (o.facebook==null) { o.facebook = document.URL; };
			};		
				
			// twitter
			if (o.twitter!=false) {
				if (o.twitter==null) { $(share).append('<div class="button twttr"><a href="http://twitter.com/share" class="twitter-share-button">Tweet</a></div>'); }
				else { $(share).append('<div class="button twttr"><a href="http://twitter.com/' + o.twitter + '" class="twitter-follow-button" data-show-count="false">Follow @' + o.twitter + '</a></div>'); };
			}
			
			// google plus
			if (o.plusone!=false) {
				if (o.plusone==null) o.plusone = document.URL;
				$(share).append('<div class="button plus"><div class="g-plusone" data-href="'+o.plusone+'" data-callback="plusClick" data-size="medium" data-count="true"></div></div>');
			};
				
			$(main).append('<div id="'+o.uniqueName+'Close" class="close"></div>');
		// modal box fully created
		
		// FIX: g:plusone
		modals[modals.length] = o.plusone;
		modals[modals.length] = o.callback;
		
		// onclick
		if (o.onclick==null) { ShowModal(); } 
		else {
			$(o.onclick).click(function() {
				var cookie = ReadCookies();
				if (cookie!=true) { ShowModal();} 
				else {
					// if element exists
					if ($('#'+o.uniqueName).length > 0){
						$('#'+o.uniqueName+'Outer').remove();
						$('#'+o.uniqueName+'Blackout').remove();
					}
					Callback(true);
				};
			});
		};


		// parse and render XFBML markup
		FB.XFBML.parse();
			
		// fired when the user likes url
		FB.Event.subscribe('edge.create', function(href) {
			if(o.facebook==href && test==0) {
				test++;
				clear();
				$.cookie('fb_'+href, 'true', { expires: 100 });
				Callback(true);
			};
		});
		// fired when the user unlikes url
		FB.Event.subscribe('edge.remove', function(href, widget) {  
			if(o.facebook==href) {
				$.cookie('fb_'+href, null);
			}
		}); 
		
		twttr.events.bind('follow', function(event) {
			if(o.twitter==event.data.screen_name && test==0) {
				test++;
				clear();
				$.cookie('twttr_'+event.data.screen_name, 'true', { expires: 100 });
				Callback(true);
			}
		});
		
		twttr.events.bind('tweet', function(event) {
			if(o.twitter==null && test==0) {
				test++;
				clear();
				$.cookie('twttr_'+document.URL, 'true', { expires: 100 });
				if (typeof o.callback == 'function') { 
					o.callback.call(this,true);
				};
			}
		});
		
	} else if (cookie==true) {
		if (o.onclick==null) { Callback(true); } 
		else {
			if (o.afterDocReady==true) { Callback(true); } 
			$(o.onclick).click(function() { Callback(true); });
		};
	};
	
	function ReadCookies() {
		if (o.facebook==null) o.facebook = document.URL;
		var cookieFB = $.cookie('fb_'+o.facebook);
		if (o.twitter==null) var cookieTW = $.cookie('twttr_'+document.URL);
		else var cookieTW = $.cookie('twttr_'+o.twitter);
		if (o.plusone==null) o.plusone = document.URL;
		if (o.plusone!=false) {
			var cookieGP1 = $.cookie('gplus_'+o.plusone);
			// FIX: repeated bad inputs in Google +1 urls
			if (o.plusone.substr(o.plusone.length - 1)=='/') {
				var fix_plusone = o.plusone.substring(0, o.plusone.length - 1);
				var cookieGP2 = $.cookie('gplus_'+fix_plusone);
			} else {
				var fix_plusone = o.plusone+'/';
				var cookieGP2 = $.cookie('gplus_'+fix_plusone);
			}
		};
		if (cookieFB =='true' || cookieGP1 == 'true' || cookieGP2 == 'true' || cookieTW =='true') return true;
		else return false;
	};
	
	function ShowModal() {
		var test = 0;
		$('#'+o.uniqueName+' .footer')	.html('Share or wait <span id="'+o.uniqueName+'Counter">'+o.count+'</span> seconds');
		$('#'+o.uniqueName+'Blackout')	.fadeTo("slow", o.opacity);
		$('#'+o.uniqueName+'Outer')		.css({'top': $(window).height()/2-$(outer).outerHeight()/2, 'left': $(window).width()/2-$(outer).outerWidth()/2})
										.fadeIn(1500);
		if (o.count!=0) {
			$('#'+o.uniqueName+'Counter').text(o.count);
			if ($('#'+o.uniqueName+'Close').is(":visible")) { 
				$('#'+o.uniqueName+'Close').hide(); 
				$('#'+o.uniqueName+'Blackout').unbind('click');
			}
			var counter = o.count;
			var interval = setInterval(function() {
				if (counter >= 0) {
					counter--;
					$('#'+o.uniqueName+'Counter').html(counter);
				};
				if (counter === 0 && o.manualClose==false) { clear(); Callback(false);  };
				if (counter === 0 && o.manualClose!=false) { ManualClose(); };
			}, 1000);
		} else { ManualClose(); };
	};
	
	function ManualClose() {
		var uniqueName = '#'+o.uniqueName;
		if (o.manualClose==true || (o.manualClose==false && o.count==0)) { $(uniqueName+' .footer').html('Feel free to close this'); }
		else { $(uniqueName+' .footer').html(o.manualClose); };
		$(uniqueName+'Close')	.fadeIn(500)
								.click(function() { clear(); Callback(false); });
		$(uniqueName+'Blackout').click(function() { clear(); Callback(false); });
	};
	
	function Callback(success) {
		if (typeof o.callback == 'function' && o.callback!=false) { 
			o.callback.call(this,success);
		};	
	}
};	

function plusClick(data) {
	if(data.state=="on" && test==0) {
		test++;
		$.cookie('gplus_'+data.href, 'true', { expires: 100 });
		clear();
		var check = $.inArray(data.href, modals)
		if (check>=0) {
			modals[check+1].call(this,true);
		}
	} else {
		$.cookie('gplus_'+data.href, null);
	}
};


function clear(){
	$('.socialmodalOuter').fadeOut(500);
	$('.blackout').fadeOut(1000);
};